package handles

import (
	"dorm-manage/cache"
	"dorm-manage/models"
	"dorm-manage/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	var user models.User
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户或密码错误",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"data": "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"data": "密码错误三次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"data": "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": "登录成功",
	})
	return

}
